/*
 * @Author: zw
 * @Date: 2020-12-08 10:17:24
 * @LastEditors: Zhang Wei
 * @LastEditTime: 2024-05-25 03:07:56
 * @FilePath: \schulte-meter\miniprogram\pages\test_page\test_login\test_login.js
 * @Description: 登录相关测试页
 */

// const $wxDecrypt = wx.$wxDecrypt;
const $wxDecrypt = () => {}

// import WXBizDataCrypt from '../../../utils/wx/decrypt/WXBizDataCrypt';
const WXBizDataCrypt = () => { }

// const { getSessionKey } = wx.$utils;
const getSessionKey = () => { }

// import { getTplId } from '../../../service/common';
const getTplId = () => { }

Page({
  /**
   * 页面的初始数据
   */
  data: {
    jsCode: '',
    encryptedData: '',
    iv: '',
    phoneNumber: '',
    appId: '',

    /*===============  模板推送  ===============*/
    tplId: [],
    tplIdShow: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let appId = wx.getAccountInfoSync().miniProgram.appId;
    this.setData({ appId });

    this.login()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () { },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () { },

  /*==============================================  逻辑  ==============================================*/

  /*==============================================  事件  ==============================================*/
  // 登录
  login() {
    wx.login({
      success: (res) => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log(res);

        this.setData({
          jsCode: res.code,
        });
      },
    });
  },

  // 获取手机号
  getPhoneNumber(e) {
    console.log(e);

    if (e.detail.errMsg === 'getPhoneNumber:fail user deny') {
      // 未成功获取到手机号
      console.log('登录失败，请同意授权');
    } else {
      let { encryptedData, iv } = e.detail;
      this.setData({
        encryptedData,
        iv,
      });
      console.log('获取手机号成功');
    }
  },

  // sessionKey
  sessionKeyChange({ detail }) {
    this.setData({
      sessionKey: detail,
    });
  },

  // 解密手机号
  decryptPhone() {
    let { appId, sessionKey, encryptedData, iv } = this.data;
    if (!sessionKey) sessionKey = getSessionKey();

    if (!sessionKey) {
      return wx.showModal({
        content: '请输入sessionKey',
        showCancel: false,
      });
    }

    /*===============  封装转换  ===============*/
    $wxDecrypt({ encryptedData, iv })
      .then((res) => {
        console.log(res);
        let { purePhoneNumber } = res;
        this.setData({
          phoneNumber: purePhoneNumber,
        });

        wx.showModal({
          content: '转换成功',
          showCancel: false,
        });
      })
      .catch((err) => {
        console.log(err);
        wx.showModal({
          content: '解密失败',
          showCancel: false,
        });
      });

    /*===============  原装转换  ===============*/
    // let pc = new WXBizDataCrypt(appId, sessionKey);
    // pc.decryptData(encryptedData, iv)
    //   .then((res) => {
    //     console.log(res);
    //     let { purePhoneNumber } = data;
    //     this.setData({
    //       phoneNumber: purePhoneNumber,
    //     });
    //   })
    //   .catch((err) => {
    //     console.log(err);
    //     wx.showModal({
    //       content: '解密失败',
    //       showCancel: false,
    //     });
    //   });
  },

  // 自提点选择
  selType() {
    let path = wx.$CONST.PAGE_PATH.SEARCH_SELF_WAY;
    let url = `${path}?orderType=today`;
    wx.$router.push({
      url,
    });
  },

  /*===============  消息模板相关  ===============*/
  // 获取模板id
  getTplId() {
    const _this = this;

    // 模拟数据
    // const tmplIds = [
    //   'eja5uFPnxHELlX_3I0niOaxcefXMNBHoVDJ5QWAXA8w',
    //   'LrjzsXJOYstBsXx2QxdD9rQ5jix9nrrKOOw8x4hwviA',
    //   'sLjrnSOLM8-xicSYPS0aU8oVjsQHT23nulvHskDpecA',
    // ];

    // 请求推送模板
    let queryData = {
      appId: wx.getAccountInfoSync().miniProgram.appId,
      typeList: ['orderDelivery', 'orderPickUp', 'orderComplete'],
    };
    getTplId(queryData).then((res) => {
      if (!res.data.ok) return false;
      let listObj = res.data.data;
      let typeList = [];
      Object.keys(listObj).forEach((key) => {
        typeList.push(listObj[key]);
      });

      _this.setData({
        tplId: typeList,
        tplIdShow: JSON.stringify(typeList),
      });

      console.log(typeList, 'typeList');
    });
  },
  // 消息推送 授权
  authSubMessage() {
    const _this = this;
    return new Promise((resolve, reject) => {
      const { tplId } = _this.data;

      if (!tplId || tplId.length === 0) {
        wx.showModal({
          content: '请先获取模板id',
          showCancel: false,
        });
        return false;
      }

      // 请求模板支付
      wx.requestSubscribeMessage({
        tmplIds: tplId,
        success(res) {
          console.log(res, 'requestSubscribeMessage success');
        },
        fail(err) {
          console.log(err, 'requestSubscribeMessage fail');
        },
        complete: function () {
          resolve();
        },
      });
    });
  },
});
